<template>
  <view class="wap dynamic">
    <!-- <view class="dynamic_con">
      <view class="txt">
        <u--textarea
          v-model="reqData.Content"
          border="bottom"
          placeholder="说说要分享的趣事~"
        ></u--textarea>
      </view>
    </view> -->

    <view class="action_con" v-if="action_list.length > 0">
      <view>选择主题</view>
      <view
        class="act"
        v-for="(ac, index) in action_list"
        :key="index"
        @click="add_act(ac)"
      >
        #{{ ac.Title }}
      </view>
    </view>
    <!-- 图片九宫格 -->
    <view
      class="imgvideo"
      v-if="localList.length == 0 || localList[0].fileType == 'image'"
    >
      <view class="item" v-for="(item, index) in localList" :key="index">
        <view class="del_con" @click.stop="delImg(index)">
          <uni-icons type="closeempty" color="#fff" size="16"></uni-icons>
        </view>
        <!-- item.netPath -->
        <image
          @click="lookimg(item.flieUrl, index)"
          :src="item.flieUrl"
          mode="aspectFill"
        />
        <!-- <view class="pro" v-if="item.pro != 100">已上传:{{item.pro + '%'}}</view> -->
      </view>
      <!-- #ifdef MP-WEIXIN -->
      <view
        class="item item_add"
        v-if="localList.length < 9"
        @click="selectImg_MP()"
      ></view>
      <canvas
        canvas-id="tranCanvas"
        class="tranCanvas"
        :style="{ width:canvasWidth+'px',height: canvasHeight + 'px' }"
      ></canvas>

      <!-- #endif -->

      <!-- #ifdef APP-PLUS -->
      <view
        class="item item_add"
        v-if="localList.length < 9"
        @click="selectImg_APP()"
      ></view>
      <!-- #endif -->
    </view>

    <!-- 视频 视频播放器 -->
    <view
      v-else
      class="video_box"
      :style="'height:' + vHight + 'rpx;width:' + vWidth + 'rpx'"
    >
      <video
        id="myVideo"
        :src="localList[0].flieUrl"
        :style="'height:' + vHight + 'rpx;width:' + vWidth + 'rpx'"
      ></video>
      <view class="del_con" @click.stop="delImg(index)">
        <uni-icons type="closeempty" color="#fff" size="16"></uni-icons>
      </view>
      <view class="pro" v-if="localList[0].pro != 100"
        >已上传:{{ localList[0].pro + "%" }}</view
      >
    </view>

    <!-- <view class="group" v-if="IsManager">
			<view class="lab">
				订场定金:
			</view>
			<view class="inp_box">
				<input type="text" v-model="reqData.OrderFee" placeholder="请输入定金">
			</view>
		</view> -->

    <!-- <view class="btm_btn wap">
      <view class="btm_tip">
        <radio
          style="transform: scale(0.7)"
          :checked="isRead"
          color="#B98B51"
        ></radio>
        用户发布动态的时候请遵守<text class="c_sed" @click="openPopupTip">
          聚农优品发布须知
        </text>
      </view>
      <view class="sendContent" @click="sub">
        <text lines="1" class="text_5">发布</text>
      </view>
      
    </view> -->
    <uni-popup ref="popupTip" type="bottom">
      <view class="tip wap">
        <view class="tit f1 fwb"> 发布须知 </view>
        <view class="txt">
          <view class="mt20"
            ><text class="f3 c2"
              >1.不得发布非法广告：包括但不限于色情推广、漏点画面，销售假冒伪劣和违禁品，利用一些违反广告法的行为推销，违反公序良俗的行为。</text
            >
          </view>
          <view class="mt20"
            ><text class="f3 c2"
              >2.不得仪容仪表不当：包括但不限于裸露上身、大面积裸纹身等，不符合审美能力的一些妆容，带有性暗示的直播内容。</text
            >
          </view>
          <view class="mt20"
            ><text class="f3 c2"
              >3.不得侵犯消费者权利：行为有很多,销售假冒伪劣产品,以次充好强迫消费者购买,销售过期产品。并且不给消费者退费,价格虚高,包括但不限于盗用、复制、直播无转播权的活动现场、录制、直播无版权的视听内容等。</text
            >
          </view>
          <view class="mt20"
            ><text class="f3 c2"
              >4.不得销售违禁品：任何人售卖违禁品会触犯法律的底线，受到法律的制裁。包括但不限于防身刀、激光笔等管制刀具;烟花爆竹、鞭炮等易燃易爆物品;含有色情、暴力、低俗等内容的产品。</text
            >
          </view>
          <view class="mt20"
            ><text class="f3 c2"
              >5.不得对未成年人有害的行为：未成年人思想还不成熟，易受诱惑。</text
            ></view
          >
        </view>
        <view class="btn mt20 mb30" @click="closePopupTip">关闭</view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { checkPornography } from "../../common/imgExamine";
export default {
  data() {
    return {
      cache_user: {},
      localList: [],
      // 视频宽高
      vWidth: 520,
      vHight: 450,
      reqData: {
        Content: "",
        Images: "",
        CompanyID: 6002,
        CatalogID: 0,
        Title: "",
        IsVideo: "",
        ActionID: 0,
        VideoInfo: "",
      },
      isRead: false,
      action_list: [],

      subject: "",
      action_id: 0,

      IsManager: false,
      range: [],
      isTip:false
    };
  },
  async onLoad(e) {
    let u = await this.$api.post("User/GetUserInfo", {
      ID: uni.getStorageSync("user").UserID,
    });
    if (u.code == 0) {
      this.cache_user = u.data;

      if (this.cache_user.IsAuth == 0) {
        let _this = this;
        uni.showModal({
          title: "温馨提示",
          content: "非注册用户不能发动态，请注册账号",
          confirmText: "关闭",
          cancelText: "注册账号",
          success: function (res) {
            if (res.confirm) {
              uni.navigateBack({
                delta: 1,
              });
            } else if (res.cancel) {
              _this.nav_to("/pages/start/start2");
            }
          },
        });
      }
    }

    await this.$api.post("/Common/Add_ViewPath", {
      Path: "dynamic_add",
      Platform: uni.getStorageSync("platform"),
    });

    if (e) {
      this.subject = e.t;
      this.action_id = e.a;

      this.reqData.ActionID = this.action_id;

      if (this.subject) {
        this.reqData.Content = "#" + this.subject + " ";
      }
    }

    let res = await this.$api.post("Company/IsCompanyAdmin");
    if (res.data) this.IsManager = true;

    await this.getActions();

    //判断用户是否注册会员
    this.checkUserAuth();
  },
  methods: {
    lookimg(url, index) {
      console.log(url, "url");
      uni.previewImage({
        urls: [url],
        current: index,
      });
    },
    async getActions() {
      let res = await this.$api.post("Action/Running");

      this.action_list = res.data;
    },
    add_act(item) {
      this.reqData.Content = "#" + item.Title + " " + this.reqData.Content;
      this.reqData.ActionID = item.ID;
    },
    openPopupTip() {
      this.$refs.popupTip.open();
    },
    closePopupTip() {
      this.$refs.popupTip.close();
    },
    delImg(index) {
      console.log(index);
      this.localList.splice(index, 1);
    },
    setRead() {
      this.isRead = !this.isRead;

      console.log(this.isRead);
    },
    // 文件选择
    selectImg_MP(index) {
      let _this = this;

      let ind = 1;

      let enableChooseNum = 9 - _this.localList.length;

      uni.chooseMedia({
        count: enableChooseNum,
        mediaType: ["image", "video"],
        sourceType: ["album", "camera"],
        maxDuration: 30,
        camera: "back",
        success: async (res) => {
          //判断：如果是视频，只取一个视频文件，并提示用户；
					console.log('res',res);

          if (res.tempFiles[0].fileType === "video") {
            let o = {
              duration: res.tempFiles[0].duration,
              fileType: res.tempFiles[0].fileType,
              tempUrl: res.tempFiles[0].thumbTempFilePath,
              // item.
              flieUrl: res.tempFiles[0].tempFilePath,
              tempKey: uni.$u.guid(8),
              pro: 0,
            };
            uni.getVideoInfo({
              src: res.tempFiles[0].thumbTempFilePath,
              success: function (image) {
                console.log("video size  ---" + JSON.stringify(image));

                let max = 560;
                if (image.height > image.width) {
                  _this.vHight = max;
                  _this.vWidth = max * (image.width / image.height);
                } else {
                  max = 600;
                  _this.vWidth = max;
                  _this.vHight = max * (image.height / image.width);
                }

                _this.reqData.VideoInfo = _this.vWidth + "|" + _this.vHight;

                console.log("video size" + _this.reqData.VideoInfo);
              },
            });
						let con = false
						res.tempFiles.forEach(v=>{
							if(_this.localList.length){
								con = _this.localList.find(item=>item.fileType != v.fileType)							
							}							
						})
						if(con) return _this.$pv.msg('只能同时发布图片或视频')
            _this.localList.push(o);

            _this.uploading(o.flieUrl, o.tempKey);

            return;
          }
          // 图片区
          for (let i = 0; i < res.tempFiles.length; i++) {
            // const base64Data = uni.getFileSystemManager().readFileSync( res.tempFiles[i].tempFilePath, 'base64')
            // // 鉴黄
            // let checkResult = await checkPornography(base64Data)
            // if(checkResult.data.conclusionType != 1) {
            //   res.tempFiles.splice(i, 1);
            //   this.isTip = true
            //   continue
            // }

            let o = {
              duration: 0,
              fileType: res.tempFiles[i].fileType,
              tempUrl: res.tempFiles[i].tempFilePath,
              flieUrl: res.tempFiles[i].tempFilePath,
              tempKey: uni.$u.guid(8),
              pro: 0,
            };
						let con = false
						res.tempFiles.forEach(v=>{
							if(_this.localList.length){
								con = _this.localList.find(item=>item.fileType != v.fileType)							
							}							
						})
						if(con) return _this.$pv.msg('只能同时发布图片或视频')
             _this.localList.push(o);
            _this.$pv.load("正在上传");
            // if (ind == 1) {
            //   _this.localList.push(o);
            // } else {
            //   _this.localList.splice(ind, 1, o);
            // }
            // _this.$pv.load("正在上传");
            // // 图片水印
            // let result = await _this.$util.addWaterMarkOfImg(
            //   "tranCanvas",
            //   res.tempFiles[i].tempFilePath,
            //   _this.logoImgInfo.path,
            //   20,
            //   20,
            //   _this.logoImgInfo.width,
            //   _this.logoImgInfo.height,
            //   o.tempKey,
            //   _this
            // );
            // if (result.imgSrc) {
            //   this.$nextTick(async ()=>{
                
            //     await _this.uploading(result.imgSrc, result.tempKey);
            //   })
              
            // } else {
            //   _this.$pv.msg("水印添加失败");
            //   return;
            // }
            await _this.uploading(o.flieUrl, o.tempKey);

            // ind = ind + 1;
          }
          if(this.isTip){
            this.$pv.msg("存在有不合规内容，以为您去除！")
          }
          console.log("上传完",_this.localList);
					
          // 超过9张则只保留9张
          if (_this.localList.length > 9) {
            _this.localList.splice(9);
            _this.$pv.msg("最多上传9张");
          }
        },
      });
    },
    selectImg_APP() {
      let _this = this;
      uni.showActionSheet({
        itemList: ["拍摄视频", "选择照片", "选择视频", "取消"],
        success: function (res) {
          if (res.tapIndex == 0) {
            uni.chooseVideo({
              sourceType: ["camera"], // 从相册、相机获取视频
              maxDuration: 300, // 最大录制时间为60s
              camera: "back", // 默认后置摄像头
              success(res) {
                console.log("选择的视频信息：", res);

                //清空已选中文件
                _this.localList = [];

                const tempFilePath = res.tempFilePath; // 临时文件路径
                // TODO: 处理选择的视频文件
                let o = {
                  duration: 0,
                  fileType: "video",
                  tempUrl: tempFilePath,
                  flieUrl: tempFilePath,
                  tempKey: uni.$u.guid(8),
                  pro: 0,
                };

                _this.localList.push(o);

                _this.uploading(o.flieUrl, o.tempKey);
              },
              fail(err) {
                console.error("选择视频失败：", err);
              },
            });
          } else if (res.tapIndex == 1) {
            let ind = 1;
            uni.chooseImage({
              // count:  允许上传的照片数量
              count: 9,
              // sizeType:  original 原图，compressed 压缩图，默认二者都有
              sizeType: ["original", "compressed"],
              sourceType: ["album"],
              success(res) {
                console.log(res);
                res.tempFiles.forEach(async (item) => {
                  let o = {
                    duration: 0,
                    fileType: "image",
                    tempUrl: item.path,
                    flieUrl: item.path,
                    tempKey: uni.$u.guid(8),
                    pro: 0,
                  };

                  if (ind == 1) {
                    _this.localList.push(o);
                  } else {
                    _this.localList.splice(ind, 1, o);
                  }
                  await _this.uploading(o.flieUrl, o.tempKey);

                  ind = ind + 1;
                });
              },
            });
            return;
          } else if (res.tapIndex == 2) {
            uni.chooseVideo({
              sourceType: ["album"], // 从相册、相机获取视频
              maxDuration: 60, // 最大录制时间为60s
              camera: "back", // 默认后置摄像头
              success(res) {
                console.log("选择的视频信息：", res);
                const tempFilePath = res.tempFilePath; // 临时文件路径
                // TODO: 处理选择的视频文件

                let o = {
                  duration: 0,
                  fileType: "video",
                  tempUrl: tempFilePath,
                  flieUrl: tempFilePath,
                  tempKey: uni.$u.guid(8),
                  pro: 0,
                };

                _this.localList.push(o);

                _this.uploading(o.flieUrl, o.tempKey);
              },
              fail(err) {
                console.error("选择视频失败：", err);
              },
            });

            return;
          }
        },
        fail: function (res) {},
      });
    },
    // 文件上传
    async uploading(url, tempKey) {
			
      const r = await this.$upload(url, async (pro) => {
        for (let i = 0; i < this.localList.length; i++) {
          if (this.localList[i].tempKey == tempKey) {
            this.localList[i].pro = await pro;
          }
        }
      });
      
      for (let i = 0; i < this.localList.length; i++) {
        if (this.localList[i].tempKey == tempKey) {
           this.localList[i].netPath = await r;
        }
      }
			
    console.log('this.localList',this.localList);
      this.$pv.closeLoad()
      console.log("upload file " + r);
    },
    async sub() {
      this.isRead = true;

      if (this.localList.length == 0) {
        this.$pv.msg("您还未添加图片或者视频!");
        return false;
      }
      this.$util.throttle(async () => {
        if (this.localList[0].fileType === "image") {
          this.reqData.IsVideo = 0;
        } else {
          this.reqData.IsVideo = 1;
        }

        this.reqData.Images = JSON.stringify(
          this.localList
            .filter((v) => v.netPath)
            .map((item) => {
              return item.netPath;
            })
        );

        this.$pv.load("正在处理");
        let newReqData = JSON.parse(JSON.stringify(this.reqData));
        newReqData.Content = this.$util.utf16ToEntities(newReqData.Content);
        if (newReqData.Content.length > 200) {
          newReqData.Content.slice(0, 200);
        }
        let res = await this.$api.post("Community/UserShare", newReqData);
        if (res.code == 0) {
          this.$pv.closeLoad();

          this.$pv.msg(res.message);

          //this.playScoreAddAudio();
					uni.$emit('update')
					this.$store.commit('changeRefresh',true)
          this.nav_back(2000);
        }
      });
    },
  },
};
</script>

<style lang="scss">
page {
  background-color: #f6f6f6;
}
.tranCanvas {
  width: 100vw;
  height: 100vh;
  opacity: 0;
  position: fixed;
  left: 0;
  top: 0;
  transform: translate(-200%, -200%);
  box-sizing: border-box;
}
.dynamic {
  margin-top: 20rpx;
  padding-top: 20rpx;
  padding-bottom: 30rpx;
  background-color: #fff;

  .group {
    display: flex;
    align-items: center;
    height: 110rpx;
    border-bottom: 1px solid #252323;
    margin-top: 30rpx;
    margin-left: 30rpx;
    margin-right: 30rpx;

    &:last-child {
      border-bottom: none;
    }

    .lab {
      padding-right: 10rpx;
      color: #fff;
      font-size: 32rpx;
    }

    .inp_box {
      flex: 1;

      input {
        width: 100%;
        text-align: right;
      }
    }

    .icon_box {
      height: 40rpx;
      width: 40rpx;
      line-height: 40rpx;
    }
  }
}

.imgvideo {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  // margin-bottom: 220rpx;

  &::after {
    height: 1px;
    width: 220rpx;
    display: block;
    content: "";
  }
}

.item {
  position: relative;
  margin-top: 15rpx;
  width: 220rpx;
  height: 220rpx;
  background-color: #f6f6f6;
  border-radius: 16rpx;

  .pro {
    position: absolute;
    top: 50%;
    width: 100%;
    transform: translateY(-50%);
    text-align: center;
    color: #3a3a3a;
  }

  image {
    height: 100%;
    width: 100%;
    border-radius: 16rpx;
  }

  .del_con {
    position: absolute;
    top: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.4);
    height: 40rpx;
    width: 40rpx;
    text-align: center;
    line-height: 40rpx;
    border-radius: 0 16rpx 0 16rpx;
  }
}

.video_box {
  margin-top: 20rpx;
  margin-left: auto;
  margin-right: auto;
  position: relative;
  background: #202020;
  display: flex;
  justify-content: center;
  border-radius: 16rpx;
  overflow: hidden;

  .pro {
    position: absolute;
    top: 50%;
    width: 100%;
    transform: translateY(-50%);
    text-align: center;
    color: #888;
  }

  .del_con {
    position: absolute;
    top: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.4);
    height: 40rpx;
    width: 40rpx;
    text-align: center;
    line-height: 40rpx;
    border-radius: 0 16rpx 0 16rpx;
  }
}

.item_add {
  position: relative;

  &::before,
  &::after {
    display: block;
    content: "";
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    position: absolute;
    height: 40rpx;
    width: 8rpx;
    border-radius: 8rpx;
    background: #dadada;
    border-radius: 10rpx;
  }

  &::before {
    transform: rotate(90deg);
  }
}

.dynamic_con {
  // margin-top: 20rpx;
  //padding-left: 32rpx;
  padding-right: 32rpx;
  //background: #202020;
  border-radius: 16rpx;

  .tit {
    height: 100rpx;
    border-bottom: 1px solid #404040;

    input {
      height: 100rpx;
      width: 100%;
      font-weight: 32rpx;
    }
  }

  .txt {
    min-height: 200rpx;
    height: 200rpx;
    margin-bottom: 20rpx;
    /deep/ .u-textarea {
      background: none !important;
      padding-left: 0 !important;
      padding-right: 0 !important;
      border-bottom: none !important;
      height: 100% !important;
      textarea {
        height: 96% !important;
      }
    }

    /deep/ .u-textarea__count {
      background: none !important;
      color: #fff !important;
    }
  }

  .act {
    line-height: 40rpx;
    color: #55aaff;
  }
}

.action_con {
  margin-top: 20rpx;
  //padding-left: 32rpx;
  padding-right: 32rpx;
  border-radius: 16rpx;

  .tit {
    height: 100rpx;
    border-bottom: 1px solid #404040;

    input {
      height: 100rpx;
      width: 100%;
      font-weight: 32rpx;
    }
  }

  .txt {
    min-height: 200rpx;
    height: 200rpx;

    /deep/ .u-textarea {
      background: none !important;
      padding-left: 0 !important;
      padding-right: 0 !important;
      border-bottom: none !important;
    }

    /deep/ .u-textarea__count {
      background: none !important;
      color: #fff !important;
    }

    /deep/ textarea {
      color: #fff !important;
    }

    /deep/ .textarea-placeholder {
      color: #a8a8a8 !important;
    }
  }

  .act {
    line-height: 40rpx;
    color: #55aaff;
  }
}

.tip {
  padding-bottom: 20rpx;
  background: #fff;
  border-radius: 10rpx 10rpx 0 0;

  .tit {
    line-height: 90rpx;
    text-align: center;
    color: #333;
  }

  .txt {
    .c2 {
      color: #666;
    }
  }

  .mb30 {
    margin-bottom: 30rpx;
  }
}

.mt20 {
  margin-top: 20rpx;
}

.btm_tip {
  font-size: 28rpx;
  margin-bottom: 40rpx;
  display: flex;
  align-items: center;
}

.btm_btn {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  box-sizing: border-box;
  height: 220rpx;
  background-color: white;
  z-index: 10;
  padding-top: 20rpx;
}

.sendContent {
  background-color: rgba(112, 110, 238, 1);
  border-radius: 44rpx;
  display: flex;
  flex-direction: column;
  padding: 16rpx 302rpx 20rpx 304rpx;
}
.text_5 {
  overflow-wrap: break-word;
  color: rgba(255, 255, 255, 1);
  font-size: 32rpx;
  font-family: PingFang-SC-Bold;
  font-weight: normal;
  text-align: right;
  white-space: nowrap;
  line-height: 52rpx;
}
.section_1 {
  flex-direction: row;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 30rpx 0;
  border-top: 2rpx solid lightgray;
  padding-top: 30rpx;
  position: relative;
  .selectContent {
    background-color: white;
    position: absolute;
    top: 100rpx;
    right: 30rpx;
    opacity: 0;
    transition: 0.5s;
    > view {
      padding: 20rpx;
    }
  }
  .diyOpacity {
    opacity: 1;
  }
}
.text_4 {
  overflow-wrap: break-word;
  color: rgba(51, 51, 51, 1);
  font-size: 32rpx;
  font-family: PingFang-SC-Medium;
  font-weight: normal;
  text-align: left;
  white-space: nowrap;
  line-height: 44rpx;
}
.image-text_1 {
  width: 348rpx;
  flex-direction: row;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.text-group_1 {
  overflow-wrap: break-word;
  color: rgba(153, 153, 153, 1);
  font-size: 32rpx;
  font-family: PingFang-SC-Medium;
  font-weight: normal;
  text-align: center;
  white-space: nowrap;
  line-height: 44rpx;
}
.thumbnail_4 {
  width: 12rpx;
  height: 24rpx;
  border: 1.2px solid rgba(196, 196, 196, 1);
  margin: 10rpx 0 10rpx 0;
}
.uni-input {
  font-size: 32rpx;
}
/deep/ .uni-select {
  border: none !important;
  min-width: 120rpx;
}
/deep/ .uni-select__input-placeholder,
.uni-select__input-text {
  font-size: 32rpx !important;
}
.diyTitle {
  font-weight: 500;
  font-size: 32rpx;
  color: #999999;
  line-height: 44rpx;
  text-align: center;
}
</style>